import json

class JsonConfig:
    # json type configuration
    def __init__(self, config_path):
        self.data = None
        self.config_path = config_path
        self.read_data()
        
    def read_data(self):
        try:
            with open(self.config_path, "r") as config_file:
                self.data = json.load(config_file)
        except (FileNotFoundError, json.decoder.JSONDecodeError):
            self.data = {}
        
    def save_data(self):
        try: 
            with open(self.config_path, 'w') as f:
                json.dump(self.data, f, indent=4)
        except FileNotFoundError:
            print("Config file not found!")
        except TypeError:
            print("Config file is not json type!")

    def get(self, key):
        try: 
            keys = key.split(".")
            data = self.data

            for k in keys:
                if isinstance(data, dict) and k in data:
                    data = data[k]
                else:
                    return None

            return data
        except (KeyError, TypeError):
            return None

    def set(self, key, value):
        keys = key.split(".")
        data = self.data

        # Traverse the keys and create nested dictionaries if necessary
        for k in keys[:-1]:
            if k not in data or not isinstance(data[k], dict):
                data[k] = {}
            data = data[k]

        # Set the final value
        data[keys[-1]] = value

        # Save the updated data
        self.save_data()
            
if __name__ == "__main__":
    config = JsonConfig("config.json")
    # print(config.data)
    
    pattern = config.data["plotting"]["update_freq"]
    print(pattern)

    print(config.get("plotting.sum_en"))
    
    config.data["pattern"] = "test"
    config.save_data()
    
    config.read_data()
    pattern = config.data["pattern"]
    print(pattern)

    config.set("pattern", "test2")
    print(config.get("pattern"))
    